package com.crux.kafka2ch.middleware.clickhouse;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class ClickHouseConfig {
    private static HikariDataSource clickHouseDataSource;
    private static JdbcTemplate jdbcTemplate;
    private ClickHouseDataSourceProperties clickHouseDataSourceProperties;

    public ClickHouseConfig(ClickHouseDataSourceProperties clickHouseDataSourceProperties) {
        this.clickHouseDataSourceProperties = clickHouseDataSourceProperties;
    }

    private HikariDataSource getClickHouseDataSource() {
        if (clickHouseDataSource == null) {
            clickHouseDataSource = new HikariDataSource();
            clickHouseDataSource.setMinimumIdle(clickHouseDataSourceProperties.getMinIdle());
            clickHouseDataSource.setMaximumPoolSize(clickHouseDataSourceProperties.getMaxPoolSize());
            clickHouseDataSource.setConnectionTimeout(clickHouseDataSourceProperties.getConnectionTimeout());
            clickHouseDataSource.setJdbcUrl(clickHouseDataSourceProperties.getJdbcUrl());
            clickHouseDataSource.setUsername(clickHouseDataSourceProperties.getUsername());
            clickHouseDataSource.setPassword(clickHouseDataSourceProperties.getPassword());
            clickHouseDataSource.setDriverClassName(clickHouseDataSourceProperties.getDriverClassName());
        }
        return clickHouseDataSource;
    }

    public JdbcTemplate getClickHouseJdbcTemplate() {
        if (jdbcTemplate == null) {
            jdbcTemplate = new JdbcTemplate(getClickHouseDataSource());
            jdbcTemplate.afterPropertiesSet();
        }
        return jdbcTemplate;
    }
}
